const cacheMap = new WeakMap();
export const useVModel = (props, propName, emit) => {
  return computed({
    get() {
      if (cacheMap.has(props[propName])) return cacheMap.get(props[propName]);
      const proxy = new Proxy(props[propName], {
        get: (target, key) => Reflect.get(target, key),
        set(target, key, value) {
          emit(`update:${propName}`, {
            ...target,
            [key]: value,
          });
          return true;
        },
      });
      cacheMap.set(props[propName], proxy);
      return proxy;
    },
    set: (value) => emit(`update:${propName}`, value),
  });
};

export const useRefModel = <T>(
  props: T,
  propName: Exclude<keyof T, Symbol>,
  emit: Function
): any => {
  return computed({
    get: () => props[propName],
    set: (value) => emit(`update:${propName}`, value),
  });
};

export const useReactiveModel = <T>(
  props: T,
  propName: Exclude<keyof T, Symbol>,
  emit: Function
): any => {
  return computed({
    get: () =>
      new Proxy(props[propName] as Object, {
        get: (target, key) => Reflect.get(target, key),
        set(target, key, value) {
          emit(`update:${propName}`, {
            ...target,
            [key]: value,
          });
          return true;
        },
      }),
    set: (value) => emit(`update:${propName}`, value),
  });
};
